<template>
	<div style="display: flex;flex-direction: row;width: 100%;">
		<div id="controlpane_container"></div>
		<el-card style="position: absolute;top: 2%;left: 2%;width: 25%;display: flex;flex-direction: column;">
			<div style="display: flex;flex-direction: column;width: 100%;">
				<span style="font-size:1.5ch;margin-top: 1%;">纬度:{{realtimedata.latitude}}</span>
				<span style="font-size:1.5ch;margin-top: 1%;">经度:{{realtimedata.longitude}}</span>
				<span style="font-size:1.5ch;margin-top: 1%;">高度:{{realtimedata.altitude}}</span>
			</div>
		</el-card>
		<el-card style="position: absolute; width: 20%;right: 2%;margin-top: 2%; display: flex;flex-direction: column;">
			<div style="display: flex;flex-direction: column;width: 100%;">
				<div style="flex-direction: row;display: flex;justify-content: space-between; align-items: center;">
					<template><i @click="back()" class="el-icon-arrow-left"></i></template>
					<span style="font-size:1.8ch;">{{dronedeviceinfo.dronedevicename}}</span>
				</div>
				<span style="font-size:1.5ch;color: gray;" v-for="(value,key) in realtimedata"
					v-show="key!='latitude'&&key!='longitude'&&key!='altitude'">{{key}}:{{value}}</span>
			</div>
			<div style="display: flex;flex-direction: column;width: 100%;">
				<el-divider></el-divider>
				<span>航线名:{{routeinfo.routename}}</span>
				<el-input v-model="routeid" placeholder="输入航线Id"></el-input>
				<div style="display: flex;flex-direction: row;width: 100%;justify-content: space-between">
					<el-button size="mini" type="text" @click="searchRoute()">标注航线</el-button>
					<el-button size="mini" type="text" @click="uploadRoute()">上传航线</el-button>
				</div>
			</div>
			<div style="display: flex;flex-direction: column;width: 100%;">
				<el-divider></el-divider>
				<el-button v-show="!controlAble" style="width: 100%;" type="danger"
					@click="getControlAccess()">申请控制权限</el-button>
				<el-tag v-show="controlAble" style="width: 100%;">已获得无人机控制权</el-tag>
				<el-button style="width: 100%; margin-top: 2%;" type="info" @click="detailControl()">打开设备控制台</el-button>
			</div>
		</el-card>
		<el-drawer title="设备操控" :visible.sync="controlDialog" direction="rtl" size="50%">
			<div style="display: flex;flex-direction: column;width: 100%;height: 100%;">
				<div style="height: 50%;width: 100%;">
					<iframe id="innnervideo" :src="streamSrc" scrolling="no" frameborder="0"
						style="height: 100%;width: 100%;"></iframe>
				</div>
				<div style="width: 100%;display: flex;flex-direction: column;">
					<el-divider></el-divider>
				</div>
				<div style="width: 100%;display: flex;flex-direction: column;">
					<span style="font-size:1.6ch;margin-top: 1%;margin-left:1% ;">硬件控制</span>
					<div
						style="width: 100%;display: flex;flex-direction: row;justify-content: space-around;margin-top: 1%;">
						<el-button size="mini" type="success" @click="controlDrone(6)">解锁电机</el-button>
						<el-button size="mini" type="warning" @click="controlDrone(7)">锁定电机</el-button>
						<el-button size="mini" type="success" @click="controlDrone(8)">开启灯光</el-button>
						<el-button size="mini" type="warning" @click="controlDrone(9)">关闭灯光</el-button>
					</div>
				</div>
				<div style="width: 100%;display: flex;flex-direction: column;">
					<span style="font-size:1.6ch;margin-top: 1%;margin-left: 1%;">飞行控制</span>
					<div
						style="width: 100%;display: flex;flex-direction: row;justify-content: space-around;margin-top: 5px;">
						<el-button size="small" type="text" @click="controlDrone(3)">上升</el-button>
						<el-button size="small" type="text" @click="controlDrone(4)">下降</el-button>
						<el-button size="small" type="text" @click="controlDrone(1)">寻路</el-button>
						<el-button size="small" type="text" @click="controlDrone(2)">悬停</el-button>
						<el-button size="small" type="text" @click="controlDrone(5)">返航</el-button>
					</div>
				</div>
				<div style="width: 100%;display: flex;flex-direction: column;">
					<span style="font-size:1.6ch;margin-top: 1%;margin-left: 1%;">姿态控制</span>
					<div
						style="width: 100%;display: flex;flex-direction: row;justify-content: space-around;margin-top: 5px;">
						<el-button size="small" type="text" @click="controlDrone(10)">左旋</el-button>
						<el-button size="small" type="text" @click="controlDrone(11)">右旋</el-button>
						<el-button size="small" type="text" @click="controlDrone(12)">左移</el-button>
						<el-button size="small" type="text" @click="controlDrone(13)">右移</el-button>
						<el-button size="small" type="text" @click="controlDrone(14)">前进</el-button>
						<el-button size="small" type="text" @click="controlDrone(15)">后退</el-button>
					</div>
				</div>
			</div>
		</el-drawer>
	</div>

</template>


<script type="text/javascript">
	import AMapLoader from "@amap/amap-jsapi-loader"
	import prop from "../property/prop.json"
	import axios from "axios"
	import mqtt from 'mqtt'

	export default {
		data() {
			return {
				map: null,
				AMap: null,
				marker: null, //点标记

				userinfo: null,
				dronedeviceinfo: {
					dronedeviceid: null,
					dronedevicename: null,
				},

				realtimedata: {},

				routeid: null,
				routeinfo: {},
				polyline: null,

				controlAble: false,

				//mqtt
				mqttclient: null,

				//控制台
				controlDialog: false,

				//直播流
				streamSrc: null,
			}
		},
		methods: {
			/*
			直播流相关方法
			*/

			play(urls) {
				var that = this

			},
			destruction() {
				//销毁对象
				if (this.player) {
					this.player.pause();
					this.player.destroy();
					this.player = null;
				}
			},

			/*
			MQTT相关方法
			*/
			initConnection() {
				var options = {
					clientId: 'user' + this.userinfo.userid,
					username: 'user' + this.userinfo.userid,
					password: this.userinfo.password,
					connectTimeout: 30 * 1000,
					clean: true,
				}
				try {
					this.mqttclient = mqtt.connect(prop.MqttUrl, options)
					if (this.mqttclient.on) {
						this.mqttclient.on("connect", () => {
							this.mqttclient.subscribe(prop.topic + this.dronedeviceinfo.dronedeviceid, (error,
								res) => {
								if (error) {
									console.log('Subscribe to topics error', error)
									return
								}
								console.log('Subscribe to topics res', res)
							})
							console.log("Connection succeeded!");
						});
						this.mqttclient.on("error", (error) => {
							this.mqttclient.end();
							console.log("Connection failed", error);
						});
						this.mqttclient.on("message", (topic, message) => {
							var data = JSON.parse(message)
							this.receiveData(data)
						});
					}
				} catch (e) {
					this.$message.error("连接出错，请重试")
				}


			},

			//获取实时data
			receiveData(e) {
				this.realtimedata = e;
				this.setMarker(e)
			},

			//设置点标记(或更改未知)
			setMarker(e) {
				if (this.marker == null) {
					var icon = new this.AMap.Icon({
						size: new this.AMap.Size(40, 50), // 图标尺寸
						image: 'https://mapleclouddata.oss-cn-beijing.aliyuncs.com/droneweb/drone_color.png', // Icon的图像
						imageSize: new this.AMap.Size(40, 50) // 根据所设置的大小拉伸或压缩图片
					})
					this.marker = new this.AMap.Marker({
						position: new this.AMap.LngLat(e.longitude, e.latitude),
						icon: icon, // 添加 Icon 实例
					})
					this.map.add(this.marker)
					this.map.setCenter(new this.AMap.LngLat(e.longitude, e.latitude))
				} else {
					this.marker.setPosition(new this.AMap.LngLat(e.longitude, e.latitude))
				}
			},
			detailControl() {
				this.controlDialog = true
			},

			controlDrone(e) {
				var that = this
				axios({
						url: prop.RequestUrl,
						method: "post",
						data: {
							requestCode: '025',
							userid: that.userinfo.userid,
							token: that.userinfo.token,
							dronedeviceid: that.dronedeviceinfo.dronedeviceid
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(function(response) {
						var data = response.data
						var result = data.result
						if (result == 1) {
							that.$message({
								message: "操作成功",
								type: "success"
							})
						} else if (result == 0) {
							that.tokenExpire()
						} else if (result == 2) {
							that.$message.error("无人机已离线")
						} else if (result == 4) {
							that.$message.error("没有控制权")
							that.controlAble = false;
						} else {
							that.$message.error("未知错误")
						}
					})
			},

			//搜索航线并标注
			searchRoute() {
				var that = this
				if (this.routeid == null) {
					this.$message.error("请输入航线id");
					return;
				}
				axios({
						url: prop.RequestUrl,
						method: "post",
						data: {
							requestCode: '026',
							userid: that.userinfo.userid,
							token: that.userinfo.token,
							routeid: that.routeid,
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(function(response) {
						var data = response.data
						var result = data.result
						if (result == 1) {
							that.routeinfo = data.data
							that.drawPath()
						} else if (result == 0) {
							that.tokenExpire()
						} else {
							that.$message.error("没有此航线")
						}
					})
			},
			//上传航线
			uploadRoute() {
				if (this.polyline == null || this.routeid == null) {
					this.$message.error("请首先标注航线")
					return
				}
				var that = this
				axios({
						url: prop.RequestUrl,
						method: "post",
						data: {
							requestCode: '021',
							userid: that.userinfo.userid,
							token: that.userinfo.token,
							dronedeviceid: that.dronedeviceinfo.dronedeviceid,
							routeid: that.routeid
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(function(response) {
						var data = response.data
						var result = data.result
						if (result == 1) {
							that.controlAble = true;
							that.$message({
								message: "上传成功",
								type: "success"
							})
						} else if (result == 0) {
							that.tokenExpire()
						} else if (result == 4) {
							that.$message.error("没有控制权限")
							that.controlAble = false;
						} else {
							that.$message.error("未知错误")
							that.controlAble = false;
						}
					})
			},

			//申请权限
			getControlAccess() {
				var that = this
				axios({
						url: prop.RequestUrl,
						method: "post",
						data: {
							requestCode: '013',
							userid: that.userinfo.userid,
							token: that.userinfo.token,
							targetdronedeviceid: that.dronedeviceinfo.dronedeviceid
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(function(response) {
						var data = response.data
						var result = data.result
						if (result == 1) {
							that.$message({
								message: "已提交申请",
								type: "success"
							})
							that.checkControl()
						} else if (result == 0) {
							that.tokenExpire()
						} else if (result == 3) {
							that.$message.error("无人机离线")
							that.controlAble = false;
						} else {
							that.$message.error("未知错误")
							that.controlAble = false;
						}
					})
			},

			//标注航线
			drawPath() {
				if (this.polyline != null) {
					this.map.remove(this.polyline)
				}
				var path = JSON.parse(this.routeinfo.routedata)
				var i, drawpath = [],
					point;
				for (i = 0; i < path.length; i++) {
					point = new this.AMap.LngLat(path[i].longitude, path[i].latitude)
					drawpath.push(point)
				}
				this.polyline = new this.AMap.Polyline({
					path: drawpath,
					showDir: true,
					strokeWeight: 5,
					lineCap: "round"
				});
				this.map.setCenter(point)
				this.map.add(this.polyline)

			},

			//初始化地图
			initMap() {
				AMapLoader.load({
					key: prop.AMapKey, //此处填入我们注册账号后获取的Key
					version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					plugins: [''], //需要使用的的插件列表，如比例尺'AMap.Scale'等
				}).then((AMap) => {
					this.AMap = AMap
					this.map = new AMap.Map("controlpane_container", { //设置地图容器id
						layers: [
							new AMap.TileLayer.Satellite(),
							new AMap.TileLayer.RoadNet()
						],
						viewMode: "2D", //是否为3D地图模式
						zoom: 15, //初始化地图级别
					});
					this.initConnection()
				}).catch(e => {
					console.log(e);
				})
			},
			checkControl() {
				//检查权限
				var that = this
				axios({
						url: prop.RequestUrl,
						method: "post",
						data: {
							requestCode: '025',
							userid: that.userinfo.userid,
							token: that.userinfo.token,
							dronedeviceid: that.dronedeviceinfo.dronedeviceid
						},
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					})
					.then(function(response) {
						var data = response.data
						var result = data.result
						if (result == 1) {
							that.dronedeviceinfo = data.data
							that.realtimedata = JSON.parse(data.data.dronemodelinstr)
							that.compareControlAccess()
						} else if (result == 0) {
							that.tokenExpire()
						}
					})
			},
			compareControlAccess() {
				//检查权限
				if (this.dronedeviceinfo != null) {
					if (this.userinfo.userid == this.dronedeviceinfo.controluserid) {
						this.controlAble = true;
						this.$message({
							type: "success",
							message: "获取控制权限成功"
						})
						return true;
					}
				}
				this.controlAble = false
				return false;
			},
			//
			//token过期
			tokenExpire: function() {
				this.$router.push({
					path: '/login',
				})
			},
			back() {
				this.$router.push({
					path: '/home',
				})
			},
		},
		beforeDestroy() {
			if (this.mqttclient) {
				this.mqttclient.end()
			}
		},
		mounted() {
			this.initMap()
			this.userinfo = JSON.parse(localStorage.getItem("userinfo"))
			this.dronedeviceinfo.dronedeviceid = this.$route.query.dronedeviceid
			this.dronedeviceinfo.dronedevicename = this.$route.query.dronedevicename
			if (this.userinfo == null || this.dronedeviceinfo.dronedeviceid == null) {
				this.$router.push({
					path: '/login',
				})
			}
			this.checkControl()
			this.streamSrc = prop.Stream + this.dronedeviceinfo.dronedeviceid

		}
	}
</script>

<style>
	html,
	body {
		height: 100%;
		margin: 0;
		padding: 0;
	}

	#controlpane_container {
		width: 100%;
		height: 100%;
	}

	.amap-logo {
		display: none;
		opacity: 0 !important;
	}

	.amap-copyright {
		opacity: 0;
	}
</style>
